package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    private static final Set<String> invalidatedTokens = ConcurrentHashMap.newKeySet();

    private static final Map<Long, Set<String>> userTokens = new ConcurrentHashMap<>();

    // 生成 Token (包含ID和Email)
    public String generateToken(UserDetails userDetails, Long userId, String email) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userId);      // 添加用户ID
        claims.put("email", email);   // 添加用户Email

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(userDetails.getUsername()) // 通常放用户名
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    // 从Token中获取用户ID
    public Long getUserIdFromToken(String token) {
        return parseToken(token).get("id", Long.class);
    }

    // 从Token中获取Email
    public String getEmailFromToken(String token) {
        return parseToken(token).get("email", String.class);
    }

    // 解析Token
    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    // 验证Token是否有效
    public boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }

    // 从Token中获取用户名
    public String getUsernameFromToken(String token) {
        return parseToken(token).getSubject();
    }

    // 检查Token是否过期
    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    // 提取过期时间
    private Date extractExpiration(String token) {
        return parseToken(token).getExpiration();
    }

    // 生成签名密钥
    private Key getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
    public void invalidateTokensForUser(Long userId) {
        Set<String> tokens = userTokens.get(userId);
        if (tokens != null) {
            invalidatedTokens.addAll(tokens);
            tokens.clear();
        }
    }
}